package com.abbas.abchat.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.abbas.abchat.AbChatApplication;
import com.abbas.abchat.R;
import com.abbas.abchat.dao.ChatMsgDao;
import com.abbas.abchat.dao.ChatTableDao;
import com.abbas.abchat.dao.impl.ChatMsgDaoImpl;
import com.abbas.abchat.dao.impl.ChatTableDaoImpl;
import com.abbas.abchat.entity.Account;
import com.abbas.abchat.entity.ChatMsg;
import com.abbas.abchat.entity.ChatTable;
import com.abbas.abchat.utils.SqlUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author abbas
 * @description: TODO
 * @date 2022/4/14 9:19
 */
public class SearchAccountListAdapter extends BaseAdapter {

    //上下文
    private Context mContext;
    //当前登录者关系表dao
    private ChatTableDao chatTableDao;
    //搜索账号数据
    private List<Account> accounts;
    //当前登录者关系
    private List<ChatTable> people;

    public SearchAccountListAdapter(Context mContext, ChatTableDao chatTableDao, List<Account> accounts) {
        this.mContext = mContext;
        this.chatTableDao = chatTableDao;
        this.accounts = accounts;
    }

    public void setPeople(List<ChatTable> people) {
        this.people = people;
    }

    @Override
    public int getCount() {
        return accounts == null ? 0 : accounts.size();
    }

    @Override
    public Object getItem(int position) {
        return accounts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null){
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.account_list,null,false);
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            viewHolder.add = (Button) convertView.findViewById(R.id.add);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Account account = accounts.get(position);

        if (TextUtils.isEmpty(account.getImgPath())){
            Glide.with(mContext)
                    .load(R.drawable.ic_people_24)
                    .transform(new RoundedCorners(16))
                    .into(viewHolder.im);
        }else {
            Glide.with(mContext)
                    .load(account.getImgPath())
                    .transform(new RoundedCorners(16))
                    .into(viewHolder.im);
        }
        if(!TextUtils.isEmpty(account.getName())){
            viewHolder.name.setText(account.getName());
        }else {
            viewHolder.name.setText(account.getAccount());
        }

        if (account.getId() == AbChatApplication.getAccount().getId()) {
            viewHolder.add.setEnabled(false);
            viewHolder.add.setText("已添加");
            viewHolder.add.setBackground(mContext.getResources().getDrawable(R.drawable.shape_gray_4));
        }

        boolean flag = false;

        if (people != null && people.size() > 0){
            for (ChatTable person : people) {
                if (person.getPeopleId() == account.getId()) {
                    viewHolder.add.setEnabled(false);
                    viewHolder.add.setText("已添加");
                    viewHolder.add.setBackground(mContext.getResources().getDrawable(R.drawable.shape_gray_4));
                    flag = true;
                    break;
                }
            }
        }
        //TODO:
        if (!flag){
            viewHolder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO: 数据库名不能含有大写单词
                    //拿到登录用户ID 及 添加用户ID(PID)
                    int id =  AbChatApplication.getAccount().getId();
                    int Pid = account.getId();
                    //拼接即将创建的数据库名称
                    String dbName = SqlUtils.CHAT_DB_HEADER + id + Pid;
                    //创建聊天数据库
                    SqlUtils.getInstance(mContext).createChatDb(id,Pid);

                    String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    //准备更新当前用户及被添加用户的关系表
                    //准备当前登录用户关系表数据
                    ChatTable chatTable = new ChatTable();
                    //对方id
                    chatTable.setPeopleId(account.getId());
                    chatTable.setLastContent(mContext.getString(R.string.add_first));
                    chatTable.setLastTime(date);
                    //两者聊天的数据库名
                    chatTable.setChatName(dbName);

                    //准备被添加用户的关系表
                    ChatTable pChatTable = new ChatTable();
                    //当前登录用户ID
                    pChatTable.setPeopleId(AbChatApplication.getAccount().getId());
                    pChatTable.setLastContent(mContext.getString(R.string.add_first));
                    pChatTable.setLastTime(date);
                    //指向同一个数据库
                    pChatTable.setChatName(dbName);

                    //开始更新
                    long result = -1;
                    try {
                        //当前登录用户关系表
                        result = chatTableDao.insert(chatTable);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //拿到被添加的用户的关系dao
                    ChatTableDao chatTableDao2 = new ChatTableDaoImpl(mContext,account.getChatTableDbName());
                    long result2 = -1;
                    try {
                        result2 = chatTableDao2.insert(pChatTable);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (result < 0 ){ //添加失败
                        Log.w("ADD COUNT ERROR!","");
                    }else {
                        viewHolder.add.setEnabled(false);
                        viewHolder.add.setText("已添加");
                        viewHolder.add.setBackground(mContext.getResources().getDrawable(R.drawable.shape_gray_4));

                        //创建一个时间戳
                        ChatMsg msgTag = new ChatMsg();
                        msgTag.setType(1);
                        msgTag.setDate(date);

                        //创建一个打招呼的消息，由被添加方发出
                        ChatMsg chatMsg = new ChatMsg();

                        chatMsg.setpId(account.getId());
                        chatMsg.setDate(date);
                        chatMsg.setContent(mContext.getString(R.string.add_first));

                        //向聊天表当中插入此打招呼数据
                        try {
                            long result4 = new ChatMsgDaoImpl(mContext,dbName).insert(msgTag);
                            long result3 = new ChatMsgDaoImpl(mContext, dbName).insert(chatMsg);
                            if (result3 >= 0){
                                Log.i("Add Friend First Time Log", "Yes");
                            }else {
                                Log.e("Add Friend First Time Log", "Error");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (result2 < 0){
                        Log.e("ADD COUNT ERROR!", "onClick: ");
                    }
                }
            });
        }

        return convertView;
    }

    static class ViewHolder{
        ImageView im;
        TextView name;
        Button add;
    }
}
